package com.micai.web;

import com.micai.entity.Book;
import com.micai.service.HelloService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * 描述：创建ConsumerController类并实现/ribbon-consumer接口.在该接口中,通过在上面创建的RestTemplate来
 * 实现对MICAI-SPRINGCLOUD-EUREKA-PROVIDER服务提供的/hello接口进行调用.可以看到这里访问的地址是服务名
 * MICAI-SPRINGCLOUD-EUREKA-PROVIDER,而不是一个具体的地址,在服务治理框架中,这是一个非常重要的特性,也符合
 * 本章一开始对服务治理的理解
 * <p>
 * Author: 赵新国
 * Date: 2017/12/21 17:11
 */
@RestController
@RequestMapping("/ribbon-consumer")
public class ConsumerController {

    /**
     * 日志组件
     */
    private static final Logger logger = LoggerFactory.getLogger(ConsumerController.class);

    /**
     * 服务提供者URL
     */
    private static final String MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL = "http://MICAI-SPRINGCLOUD-EUREKA-PROVIDER";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String helloConsumer() {
        /*ResponseEntity<String> responseEntity  = restTemplate.getForEntity(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL +"/hello", String.class);
        String body = responseEntity.getBody();*/
        String body = helloService.helloService();
        return body;
    }

    @GetMapping("/index")
    public String indexConsumer() {
        ResponseEntity<String> responseEntity  = restTemplate.getForEntity(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL + "/index", String.class);
        String body = responseEntity.getBody();
        return body;
    }

    /**
     * 服务消费者-GET方法
     * @return
     */
    @GetMapping("/getBook")
    public Book getBookConsumer() {
        Book body = restTemplate.getForObject(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL + "/getBook", Book.class);
        logger.info("book: {}", body);
        return body;
    }

    /**
     * 服务消费者-POST方法
     * @return
     */
    @PostMapping("/addBook")
    public Book addBookConsumer(@RequestBody Book book) {
        ResponseEntity<Book> responseEntity = restTemplate.postForEntity(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL + "/addBook", book, Book.class);
        return responseEntity.getBody();
    }

    /**
     * 服务消费者-PUT方法
     * @param book
     */
    @PutMapping("/putBook")
    public void putBookConsumer(@RequestBody Book book) {
        restTemplate.put(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL + "/putBook/{1}", book, book.getId());
    }

    /**
     * 服务消费者-DELETE方法
     * @param book
     */
    @DeleteMapping("/deleteBook")
    public void deleteBookConsumer(@RequestBody Book book) {
        restTemplate.delete(MICAI_SPRINGCLOUD_EUREKA_PROVIDER_URL + "/deleteBook/{1}", book.getId());
    }

}
